package com.algorithms;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import utils.ListUtils;

public class TwitterApi {

	public static Twitter twitter;

	public static boolean setUser(String user, String pass) {
		TwitterApi.twitter = new TwitterFactory().getInstance(user, pass);

		User u = null;
		int i = 0;
		while (i < 5 && u == null) {
			try {
				u = twitter.verifyCredentials();

			} catch (TwitterException e) {
				if (e.getStatusCode() == 401)// it wasn´t validated.
					return false;
				else {
					i++;
					try {
						Thread.sleep(2000); // wait 2 seconds and try again.
					} catch (InterruptedException e1) {
					}
				}
			}
		}

		if (u != null) return true;
		return false;
	}

	/**
	 * Devuelve los ids de todos los usuarios seguidos por el usuario ingresado.
	 * 
	 * @param twitter
	 */
	public static List<Integer> getSeguidos() {

		int tried = 0;
		while (tried < 5) {

			try {
				return ListUtils.arrayToList(TwitterApi.twitter.getFriendsIDs()
						.getIDs());

			} catch (TwitterException e) {
				tried = resolveException(tried, e);
			}
		}

		return new ArrayList<Integer>();
	}

	public static List<Integer> getSeguidoresFromUser(Integer userId) {
		int[] ids = null;

		while (ids == null) {
			try {
				ids = TwitterApi.twitter.getFollowersIDs(userId).getIDs();
			} catch (TwitterException e) {
				if (e.exceededRateLimitation()) {
					try {
						System.out
								.println(new Date()
										+ " durmiendo 1 hora hasta q twitter me habilite");
						Thread.sleep(3600000);// sleep 1 hour.
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
				} else {
					return new ArrayList<Integer>();
				}
			}
		}

		return ListUtils.arrayToList(ids);
	}

	public static User showUser(Integer userId) {

		int tried = 0;

		while (tried < 5) {
			try {
				return TwitterApi.twitter.showUser(userId);
			} catch (TwitterException e) {
				tried = resolveException(tried, e);
			}
		}
		return null;
	}

	public static List<Status> getUserStatus(Integer userId) {

		int tried = 0;
		while (tried < 5) {
			try {
				return twitter.getUserTimeline(userId);

			} catch (TwitterException e) {

				tried = resolveException(tried, e);
			}
		}
		return new ArrayList<Status>();
	}

	/**
	 * Get's the favorites tweets from the topTweet user.
	 * 
	 * @return
	 */
	public static List<Status> getTopTweetsFavorites(int page, String user) {

		int tried = 0;
		while (tried < 5) {
			try {
				// Integer topTweetsId = 113425681;
				return twitter.getFavorites(user, page);

			} catch (TwitterException e) {
				tried = resolveException(tried, e);
			}
		}
		return new ArrayList<Status>();
	}

	public static List<User> getUsersById(List<ScoredUser> sUsers) {

		List<User> users = new ArrayList<User>();

		if (sUsers != null) {
			for (ScoredUser sUser : sUsers) {
				User u = showUser(sUser.getId());
				if (u != null) users.add(u);
			}
		}
		return users;
	}

	private static int resolveException(int tried, TwitterException e) {
		try {
			if (e.exceededRateLimitation()) {

				tried = 0; // reset the times we tried.
				System.out.println(new Date()
						+ " durmiendo 1 hora hasta q twitter me habilite");
				Thread.sleep(3600000);// sleep 1 hour.

			} else {
				System.out.println("Algo paso en el intento: " + tried);
				tried++; // increment i.
				Thread.sleep(5000); // sleep 5 seconds.
			}
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		return tried;
	}
}